package com.wjl.shop.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjl.shop.dao.StockOrderDao;
import com.wjl.shop.entity.StockOrder;
import com.wjl.shop.entity.SumOrder;
import com.wjl.shop.dao.SumOrderDao;
import com.wjl.shop.service.SumOrderService;
import com.wjl.shop.util.ExportExcel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 汇总表信息(SumOrder)表服务实现类
 *
 * @author makejava
 * @since 2021-10-07 14:07:23
 */
@Service("sumOrderService")
public class SumOrderServiceImpl implements SumOrderService {
    public final static int SUM_CODE=5;
    public final static int SUM_OK=6;
    public final static String EXCEPTION_MESSAGE_CODE="合并订单状态不正确！";
    @Resource
    private SumOrderDao sumOrderDao;

    @Resource
    private StockOrderDao stockOrderDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SumOrder queryById(Integer id) {
        return this.sumOrderDao.queryById(id);
    }

    @Override
    @Cacheable(cacheNames = "sumOrders",key = "#sumOrder+'-'+#currentPage+'-'+#pages")
    public Map<String, Object> queryAllBySumOrder(SumOrder sumOrder,Integer currentPage,Integer pages) {
        final HashMap<String, Object> map = new HashMap<>();
        try {
            Double price = sumOrderDao.queryTotalPrice(sumOrder);
            Double volume = sumOrderDao.queryTotalVolume(sumOrder);
            PageHelper.startPage(currentPage,pages);
            List<Map<String, Object>> list = sumOrderDao.queryAllBySumOrder(sumOrder);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            map.put("status","ok");
            map.put("message","查询成功!");
            map.put("allTotalPrice",price);
            map.put("allTotalVolume",volume);
            map.put("data",pageInfo.getList());
            map.put("currentPage",currentPage);
            map.put("total",pageInfo.getTotal());
            return map;
        }catch (Exception e){
            map.put("status","fail");
            map.put("message","查询失败.");
            map.put("data",e.toString());
            map.put("currentPage",currentPage);
            map.put("total",0);
            return map;

        }
    }

    @Override
    public HSSFWorkbook exportSumOrder(List<Integer> ids) {
        try {
            final List<SumOrder> sumOrders = sumOrderDao.selectSumOrdersByIds(ids);
            final HSSFWorkbook export = ExportExcel.export(sumOrders);
            return  export;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<SumOrder> queryAllByLimit(int offset, int limit) {
        return this.sumOrderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param sumOrders 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class,Error.class})
    @CacheEvict(cacheNames = {"sumOrders","stockOrder"},allEntries = true)
    public Map<String,Object> insert(List<SumOrder> sumOrders) {
        HashMap<String, Object> map = new HashMap<>();
        try{
            if(sumOrders.size()<=0){throw new RuntimeException();}
            //对列表中所有的汇总订单进行保存
            while (sumOrders.size()>0) {
                SumOrder sumOrder = sumOrders.get(0);
                String orderCode = sumOrder.getOrderCode();
                //分割出所有备货订单编号
                String[] codes = orderCode.split("[" + StockOrderServiceImpl.SPLIT_CHAR + "]");
                //查询汇总订单的成员值
                List<Map<String, Object>> list = stockOrderDao.queryListByStockOrderCodes(Arrays.asList(codes));
                System.out.println(list.size());
                //check，检查其成员是否都可汇总
                for (Map<String, Object> data : list) {
                    System.out.println(data);
                    String code = (String) data.get("orderCode");
                    Integer stateCode = (Integer) data.get("stateCode");
                    if (stateCode != SUM_CODE) {
                        throw new RuntimeException(EXCEPTION_MESSAGE_CODE);
                    }
                    //更改状态为已汇总
                    StockOrder stockOrder = new StockOrder();
                    stockOrder.setOrderCode(code);
                    stockOrder.setStateCode(SUM_OK);
                    stockOrderDao.update(stockOrder);
                }
                //全部检查完成后保存汇总单,生成调拨单号
                sumOrder.setTransferOrderNumber("DPD"+System.currentTimeMillis());
                this.sumOrderDao.insert(sumOrder);
                //下一条
                sumOrders.remove(0);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
        map.put("status","ok");
        map.put("message","汇总成功!");
        map.put("data",null);
        return map;
    }

    /**
     * 修改数据
     *
     * @param sumOrder 实例对象
     * @return 实例对象
     */
    @Override
    public SumOrder update(SumOrder sumOrder) {
        this.sumOrderDao.update(sumOrder);
        return this.queryById(sumOrder.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sumOrderDao.deleteById(id) > 0;
    }
}
